package com.spring;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server_tcp {
    private static List<Socket> clients = new ArrayList<>();

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(12345)) {
            System.out.println("服务器启动，等待客户端连接...");
            while (true) {
                Socket socket = serverSocket.accept();
                synchronized (clients) {
                    clients.add(socket);
                }
                System.out.println("客户端已连接: " + socket.getInetAddress());
                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class ClientHandler implements Runnable {
        private Socket socket;

        ClientHandler(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                String msg;
                while ((msg = in.readLine()) != null) {
                    System.out.println("收到消息: " + msg);
                    // 转发消息给其他客户端
                    synchronized (clients) {
                        for (Socket client : clients) {
                            if (client != socket) {
                                PrintWriter out = new PrintWriter(client.getOutputStream(), true);
                                out.println(msg);
                            }
                        }
                    }
                }
            } catch (IOException e) {
                System.out.println("客户端断开: " + socket.getInetAddress());
            } finally {
                synchronized (clients) {
                    clients.remove(socket);
                }
                try { socket.close(); } catch (IOException ignored) {}
            }
        }
    }
}
